/**
 * Authenticate.jsx
 * 鉴权登录页
 *
 * created by qiuwei
 * version 1.0.0
 * 2016年03月15日
 */

import React from 'react';
import { connect } from 'react-redux';
import { authenticate, showError, setAutoAuthenticate } from '../actions/authentication';
import { reset as filterReset } from '../actions/filter';
import { switchSubView } from '../actions/level3Navigator';
import { NONE } from '../../../constants/area';

import { Login } from '../components/smart';
import { push } from 'react-router-redux';
import bgImageUrl from '../../resources/login-bg.png';

import * as AuthenticateStyle from './Authenticate.less';

class Authenticate extends React.Component {
	constructor(props) {
		super(props);
	}

	componentDidMount() {
		let { dispatch } = this.props;
		dispatch(filterReset())
		dispatch(switchSubView(NONE))
	};

	handleLogin = ({ userName, password, securityCode, isAutoAuthenticate })=>{
		let { dispatch, authentication } = this.props;
		let { pwdErrorCount } = authentication;

		if (__DEV__)
			console.log(pwdErrorCount, securityCode, authentication);

		if (!userName) 
			return dispatch(showError('请输入11位手机号'));
		else if (!password)
			return dispatch(showError('请输入密码'));
		else if (!securityCode && pwdErrorCount >= 3)
			return dispatch(showError('请输入验证码'));
		else {
			dispatch(setAutoAuthenticate(!!isAutoAuthenticate));

			return dispatch(authenticate({ userName, password, securityCode, isAutoAuthenticate }, () => {
				dispatch(push('/app/navigator'));
			}));
		}
	};

	render() {
		let { authentication } = this.props;
		let { message, pwdErrorCount, codeArea } = authentication
		return (
			<div className={AuthenticateStyle.authenticateContainer} >
				<div className={AuthenticateStyle.authenticate}>
					{false && <img src={bgImageUrl} alt='背景图' />}
					<Login 
						error={message}
						onLogin={this.handleLogin} 
						showSecurityCode={pwdErrorCount >= 3} 
						userNamePlaceHolder="手机号登录" 
						verificationCodePlaceHolder="验证码" 
						passwordPlaceHolder='请输入密码' 
						forgetPasswordUrl='/a/fpporgetPassword'
						securityCodeUrl={codeArea.url} />
				</div>
			</div>
		);
	}
}

export default connect((state) => ({
	authentication: state.authentication
}))(Authenticate);